//
//  SYHomeViewController.swift
//  SingWeibo
//
//  Created by shiying on 15/12/15.
//  Copyright © 2015年 shiying. All rights reserved.
//

import UIKit
import SVPullToRefresh

enum SYStatusCellReuseIdentifier: String {
    case SYStatusForwardCell = "SYStatusForwardCell" ///< 原创Cell的标识
    case SYStatusNormalCell = "SYStatusNormalCell"  ///< 转发Cell的标识
}


class SYHomeViewController: SYBaseViewController, SYStatusCellDelegate {
    

    
    /// 定义标识符
//    private let ReuseIdentifier = "ReuseIdentifier"

    var statuses :[SYStatus]? {
        didSet {
            /// 刷新数据,一般都是在这里刷新数据
            self.tableView.reloadData()
        }
    
    } // 设置模型属性
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        


        // 设置导航栏
        setupNav()

        prepareUI()
        
        refreshControl = SYRefreshControl()
        
        /// 监听刷新事件
        refreshControl?.addTarget(self, action: "loadStatus", forControlEvents: UIControlEvents.ValueChanged)
        
        /// 进入刷新状态，但是并不触发 ValueChange 改变
        refreshControl?.beginRefreshing()
        
        /// 自动触发ValueChange 事件
        refreshControl?.sendActionsForControlEvents(UIControlEvents.ValueChanged);
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "pictureSelect:", name: SYStatusPictureViewCellSelectNotification, object: nil)
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "popoverDismiss", name: CZPresentationControllerDismissNotificaiton, object: nil)

    }
    /// 通知方法
    func pictureSelect(notification: NSNotification) {
        guard let indexPath = notification.userInfo?[SYStatusPictureViewCellSelectIndexPathKey] as? NSIndexPath else{
            print("下标为空")
            return
        }
        guard let models = notification.userInfo?[SYStatusPictureViewCellSelectModelsKey]  as? [SYPhotoBrowserModel] else {
            print("没有url")
            return
        
        }
        
        let photoBrowserVC = SYPhotoBrowserViewController(indexPath: indexPath, models: models)
        
        photoBrowserVC.transitioningDelegate = photoBrowserVC
        photoBrowserVC.modalPresentationStyle = UIModalPresentationStyle.Custom
        presentViewController(photoBrowserVC, animated: true, completion: nil)
        
        
        print("到这里来")
    
    }
    
    // 加载数据
    func loadStatus() {
        let since_id = statuses?.first?.id ?? 0
        let max_id = 0
        
        SYStatus.loadStatusModel(since_id, max_id: max_id) { (statuses, error) -> () in

            self.refreshControl?.endRefreshing()
            if error != nil {
                print("微博数据出错")
                return
            }
            
            let count = statuses?.count ?? 0
            
            if since_id > 0 {
                self.setupTipView(count)
            }
            
            if count == 0 {
                print("没有加载到微博数据")
                return
            }
            
            /// 如果刷新数据有id > since_id 那就是拼接上去
            if since_id > 0 {
                self.statuses = statuses! + self.statuses!
                print("刷新了\(count)条微博数据")
            } else {
                /// 赋值微博数据
                self.statuses = statuses
                // 显示加载更多 菊花
                self.tableView.showsInfiniteScrolling = true
            }

        }
    }
    
    func loadMoreStatus() {
    
        let since_id = 0
        let max_id = statuses?.last?.id ?? 0
        SYStatus.loadStatusModel(since_id, max_id: max_id) { (statuses, error) -> () in
            
            // 结束刷新
            self.tableView.infiniteScrollingView.startAnimating()
            
            if error != nil { // 如果有错误就返回
                return
            }
            
            let count = statuses?.count ?? 0
            if count == 0 {
            
                return // 如果0条微博，就直接返回
            }
            
            if max_id > 0 {
                self.statuses = self.statuses! + statuses!
            }
            print("上拉加载到\(count)条更多数据")
        }
    
    }
    
    func prepareUI() {
        // 设置tabView的行高
        //        tableView.rowHeight = 300
        
        self.tableView.estimatedRowHeight = 200
        
        //        tableView.rowHeight = UITableViewAutomaticDimension
        
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        
        /// 注册原创Cell
        tableView.registerClass(SYStatusNormalCell.self, forCellReuseIdentifier: SYStatusCellReuseIdentifier.SYStatusNormalCell.rawValue)
        /// 注册转发Cell
        tableView.registerClass(SYStatusForwardCell.self, forCellReuseIdentifier: SYStatusCellReuseIdentifier.SYStatusForwardCell.rawValue)
        
        
        /// 添加这个闭包才会出现菊花，拉到最后一行cell 就会刷新
        tableView.addInfiniteScrollingWithActionHandler { () -> Void in
            self.loadMoreStatus()
        }
        // 先不显示上拉加载菊花
        tableView.showsInfiniteScrolling = false
        tableView.addSubview(tipView)
        
        tipView.transform = CGAffineTransformMakeTranslation(0, -500)
    
    }
    
    //MARK: - 设置TipView的动画
    func setupTipView(count: Int) {
        self.tipView.text = "有\(count)条微博数据更新"
        [UIView .animateWithDuration(1.5, animations: { () -> Void in
            self.tipView.transform = CGAffineTransformIdentity;
            }, completion: { (_) -> Void in
                [UIView .animateWithDuration(2.5, animations: { () -> Void in
                    self.tipView.transform = CGAffineTransformMakeTranslation(0, -500)
                })]
        })]

    }
    
    //MARK: - 设置导航栏
    func setupNav() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendsearch")
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop")
        
        // 设置昵称 POPView
        let screen_name = SYUseAccount.loadUserAccount()?.screen_name ?? "哈哈"
        let titleButton = SYHomeTitleButton(title: screen_name)
        navigationItem.titleView = titleButton


        /// 监听点击事件
        titleButton.addTarget(self, action: "titleButtonClick:", forControlEvents: UIControlEvents.TouchUpInside)
    }
    
    // MARK: - 数据源方法和代理
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
//        print("statuses条数\(statuses?.count)")
        return self.statuses?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let status =  statuses![indexPath.row]// 获得微博数据
        
        let cellID = status.cellID()// 判断是否转发微博
        
        let cell = tableView.dequeueReusableCellWithIdentifier(cellID) as! SYStatusCell
        
        print("stauts---cell \(status)")
        
        cell.status = status
        
        cell.delegate = self
        
        return cell

    }
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        let status = self.statuses![indexPath.row]
        
        if status.rowHeight != nil {
        
            return status.rowHeight! // 缓存的高，因为已经计算过了
        }
        let cellID = status.cellID()
        
        let cell = tableView.dequeueReusableCellWithIdentifier(cellID) as! SYStatusCell
        
        
        let rowHeiht = cell.rowHeiht(status) // cell 计算好的高，返回给模型
        
        status.rowHeight = rowHeiht // cell 计算好的高
        
        return rowHeiht // 返回的高
        
    }
    
    /// 选中的Cell
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        
        let status = statuses![indexPath.row]
        let detailVC = SYDetailsViewController()
        detailVC.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(detailVC, animated: true)
        detailVC.status = status
        
    }
    
    private lazy var tipView: UILabel = {
        let label = UILabel(frame: CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: 44))
        label.backgroundColor = UIColor.orangeColor()
        label.textColor = UIColor.whiteColor()
        label.font = UIFont.systemFontOfSize(16)
        label.textAlignment = NSTextAlignment.Center
        
        return label
    }()
    
    //MARK: - 代理方法
    func forwradOnTheClick(status: SYStatus) {
        let detailVC = SYDetailsViewController()
        detailVC.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(detailVC, animated: true)
        
        detailVC.status = status
    
    }
    // MARK: - 通知
    func popoverDismiss() {
        let button = navigationItem.titleView as! SYHomeTitleButton
        titleButtonClick(button)
    
    }
    
    
    // MARK: - titleButton点击事件
    func titleButtonClick(titleButton: UIButton) {
        
        titleButton.selected = !titleButton.selected// 点击后取反，为了下面的图片旋转
        UIView.animateWithDuration(0.25) { () -> Void in
            titleButton.imageView?.transform = titleButton.selected ? CGAffineTransformIdentity : CGAffineTransformRotate(CGAffineTransformIdentity, CGFloat(M_PI - 0.0001))
        }

        // 跳转到popoverVC
        if titleButton.selected {
            
            let sb = UIStoryboard(name: "SYPopoverViewController", bundle: nil)
            let popoverVC = sb.instantiateViewControllerWithIdentifier("PopoverID")
            
            // 直接modal出来的的屏幕大小一样，要转场动画来控制modal出来的view的大小
            popoverVC.transitioningDelegate = self
            popoverVC.modalPresentationStyle = UIModalPresentationStyle.Custom // 自定义
            
            presentViewController(popoverVC, animated: true, completion: nil)
            
        }
    }
}

extension SYHomeViewController: UIViewControllerTransitioningDelegate {

    // 返回一个控制器的展现的对象， 可以设置modal出来的控制器的大小
    func presentationControllerForPresentedViewController(presented: UIViewController, presentingViewController presenting: UIViewController, sourceViewController source: UIViewController) -> UIPresentationController? {
        
        return SYPresentationController(presentedViewController: presented, presentingViewController: presenting)
    }
    
    // 返回一个控制modal时的对象
    func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        // 创建一个类实现UIViewControllerAnimatedTransitioning
        // 用这个类创建对象，并返回
        return SYPopoverAnimation()
    }
    
    func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        return SYDismissAnimation()
    }
}
